using System.IO;
using Lucene.Net.Store;
using Directory=Lucene.Net.Store.Directory;

namespace LuceneSearch.Indexer
{
    public class BufferedLuceneIndexWriter : IIndexWriter
    {
        private readonly IIndexWriter indexWriter;
        private IIndexWriter ramIndexWriter;

        public BufferedLuceneIndexWriter(Directory directory)
        {
            indexWriter = new LuceneIndexWriterWrapper(directory);
            ramIndexWriter = new LuceneIndexWriterWrapper(new RAMDirectory()); 
        }

        public void IndexFile(FileInfo info)
        {
            ramIndexWriter.IndexFile(info);

            if(ramIndexWriter.GetDocumentCount() > 1000)
                FlushBuffer();
        }

        public int GetDocumentCount()
        {
            FlushBuffer();
            return indexWriter.GetDocumentCount();
        }

        public void Optimize()
        {
            FlushBuffer();
            indexWriter.Optimize();
        }

        public void Close()
        {
            FlushBuffer();
            indexWriter.Close();
        }

        public void AddIndexes(Directory[] dirs)
        {
            indexWriter.AddIndexes(dirs);
        }

        public Directory GetDirectory()
        {
            FlushBuffer();
            return indexWriter.GetDirectory();
        }

        private void FlushBuffer()
        {
            if(ramIndexWriter.GetDocumentCount() == 0) return;

            AddIndexes(new[] { ramIndexWriter.GetDirectory() });
            ramIndexWriter.Close();

            ramIndexWriter = new LuceneIndexWriterWrapper(new RAMDirectory());
        }
    }
}